package com.feifan.utils;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author Donald
 * @create 2019-03-20 1:17
 * JSON 工具类
 */
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtils(){}
    /**
     * 将对象转换为Json字符串
     *
     * @param object 待转换的对象
     * @return JSON 字符串
     * @throws IOException 转换异常
     */
    public static String getJSONString(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将JSON 串转换为对象
     *
     * @param target  目标对象
     * @param jsonStr JSON字符串
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T getJsonObject(Class<T> target, String jsonStr) throws IOException {
        return objectMapper.readValue(jsonStr, target);
    }

    /**
     * @param jsonStr       json串
     * @param typeReference new TypeReference<T>(){}
     * @return T = HashMap<Integer,UserDTO> 复杂对象
     * @throws IOException
     */
    public static Object getMapObject(String jsonStr, TypeReference type) throws IOException {
        return objectMapper.readValue(jsonStr,type);
    }

    /**
     * 获取objectMapper 对象
     *
     * @return
     */
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
}
